/**
 * 人才库-加入/移出高级库modal
 */
import React from 'react';
import { Modal, Form, Input, Select, Spin, message } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import { getEmployeeInfoList } from '@/services/components/userform';
import { onAddSenior, onRemoveSenior } from '@/pages/Recruitment/TalentsManagement/service';
import styles from '@/pages/Recruitment/containers/operate/index.less';

const FORM_DEFAULT_LAYOUT = {
    labelCol: {
        span: 6
    },
    wrapperCol: {
        span: 15
    }
};
const { TextArea } = Input;
const { Option } = Select;
// eslint-disable-next-line max-len
const MoreOperateModal = ({ form, talentCode, onOk, visible = false, operateType, defaultNoticeEmployee = [], ...rest }) => {
    // const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    // const { companyId } = user;
    const { getFieldDecorator, validateFields, resetFields } = form;
    // 获取人员
    const { data: employeeList, loading: employeeLoading } = useRequest(
        () => {
            if (visible) {
                // return getEmployeeInfoList({
                //     getChildByOrganizationCodes: [companyId]
                // });
                return getEmployeeInfoList();
            }
            return Promise.resolve({ code: 10000, data: [] });
        },
        {
            refreshDeps: [visible],
            initialData: [],
            ...defaultFormatResult
        }
    );
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const handleOk = () => {
        validateFields(async (err, values) => {
            console.log(values);
            if (err) {
                return;
            }
            try {
                setSubmitLoading(true);
                const params = {
                    talentCode,
                    reason: values.reason,
                    noticeEmployees: values?.noticeEmployeeCodeList ?? []
                };
                const { code, msg } = operateType === 'add' ? await onAddSenior(params) : await onRemoveSenior(params);
                if (code === 10000) {
                    message.success(operateType === 'add' ? '此简历已成功加入高级库！' : '此简历已成功移出高级库！');
                    onOk();
                } else {
                    message.error(msg);
                }
                setSubmitLoading(false);
            } catch (e) {
                setSubmitLoading(false);
                console.log(e, '高级库操作失败！');
            }
        });
    };
    React.useEffect(() => {
        if (visible && defaultNoticeEmployee.length && employeeList.length) {
            const noticeEmployeeCodeList = defaultNoticeEmployee.filter(item =>
                employeeList.filter(e => e.employeeCode === item)
            );
            form.setFieldsValue({
                noticeEmployeeCodeList
            });
        }
    }, [visible, employeeList.length]);
    return (
        <Modal
            {...rest}
            visible={visible}
            width={720}
            onOk={handleOk}
            confirmLoading={submitLoading}
            destroyOnClose
            afterClose={() => {
                resetFields();
            }}
            className={styles.modalWrap}
        >
            <Spin spinning={employeeLoading}>
                <Form {...FORM_DEFAULT_LAYOUT} className={styles.modalFormWrap}>
                    <Form.Item label="通知人员">
                        {getFieldDecorator(
                            'noticeEmployeeCodeList',
                            {}
                        )(
                            <Select
                                mode="multiple"
                                style={{ width: '100%' }}
                                placeholder="请选择通知人员"
                                allowClear
                                optionFilterProp="children"
                                getPopupContainer={triggerNode => triggerNode.parentElement}
                            >
                                {employeeList?.map(item => (
                                    <Option value={item.employeeCode} key={item.employeeCode}>
                                        {item.employeeName}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Form.Item>
                    <Form.Item label="理由">
                        {getFieldDecorator('reason', {
                            initialValue: '',
                            rules: [
                                {
                                    required: true,
                                    message: '理由不能为空'
                                }
                            ]
                        })(<TextArea placeholder="请输入理由" autoSize={{ minRows: 3, maxRows: 6 }} maxLength={200} />)}
                    </Form.Item>
                </Form>
            </Spin>
        </Modal>
    );
};

export default Form.create()(MoreOperateModal);
